package com.bizdroid.unutturma.activity;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import com.bizdroid.unutturma.R;
import com.bizdroid.unutturma.model.ReminderItem;
import com.bizdroid.unutturma.service.LocationService;
import com.bizdroid.unutturma.utility.ReminderAdapter;
import com.bizdroid.unutturma.utility.Utility;


public class ReminderActivity extends Activity {
	/** Called when the activity is first created. */

	private static final String TAG = "ReminderActivity";
	private ArrayList<ReminderItem> reminderList;
	private ListView remindListView;
	private ReminderAdapter listAdapter;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		 Log.d(TAG, "onCreate: starting srvice");
	     startService(new Intent(this, LocationService.class));
		
		// Find the ListView resource.
		remindListView = (ListView) findViewById(R.id.remindListView);

		
		reminderList = Utility.getReminderList(this);
		
		
		// Create ArrayAdapter using the reminder list.
		listAdapter = new ReminderAdapter(reminderList, this);

		// Set the ArrayAdapter as the ListView's adapter.
		remindListView.setAdapter(listAdapter);

		Button btnAdd = (Button) findViewById(R.id.btnAdd);

		// Listening to add button event
		btnAdd.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
				// Starting a new Intent
				Intent nextScreen = new Intent(getApplicationContext(),
						NewReminderActivity.class);
				startActivity(nextScreen);

			}
		});

		//listening remindListView item click
		remindListView
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					public void onItemClick(AdapterView<?> a, View v,
							int position, long id) {
						AlertDialog.Builder adb = new AlertDialog.Builder(
								ReminderActivity.this);
						adb.setMessage("Unutmak istedigine emin misin? ");
						final int positionToRemove = position;
						adb.setNegativeButton("HAYIR", null);
						adb.setPositiveButton("EVET",
								new AlertDialog.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										deleteReminderItem(positionToRemove);
										listAdapter.notifyDataSetChanged();
									}
								});
						adb.show();
					}
				});

	}

	/**
	 * Removes reminder from list that feeds  remindListView and sharedPreferences.
	 * @param positionToRemove
	 */
	public void deleteReminderItem(int positionToRemove) {
		ReminderItem item = reminderList.get(positionToRemove);
		reminderList.remove(positionToRemove);
		Utility.deleteReminderItem(item, this);
	}
}
